<template>
  <ContentWrap>
    <!-- 搜索工作栏：保留原始内容 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="航机员" prop="flightCrew">
        <el-input
          v-model="queryParams.flightCrew"
          placeholder="请输入航机员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港航班" prop="inboundFlight">
        <el-input
          v-model="queryParams.inboundFlight"
          placeholder="请输入进港航班"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="预落时间" prop="preLandingTime">
        <el-input
          v-model="queryParams.preLandingTime"
          placeholder="请输入预落时间(HHmm)"
          clearable
          @input="handleTimeInput('preLandingTime', $event)"
          @blur="handleTimeBlur('preLandingTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="实落时间" prop="inboundTime">
        <el-input
          v-model="queryParams.inboundTime"
          placeholder="请输入实落时间(HHmm)"
          clearable
          @input="handleTimeInput('inboundTime', $event)"
          @blur="handleTimeBlur('inboundTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-input
          v-model="queryParams.depTime"
          placeholder="请输入起飞时间(HHmm)"
          clearable
          @input="handleTimeInput('depTime', $event)"
          @blur="handleTimeBlur('depTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="queryParams.recordDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择记录日期"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="addAllToSchedule"
          v-hasPermi="['distm:schedule-record:create']"
        >
          全部添加到今日计划
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 获取最新
        </el-button>
        <el-button type="primary" plain @click="openColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：虚拟化表格 -->
  <ContentWrap>
    <div style="height: 62vh">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
            :row-height="70"
            :row-class="tableRowClassName"
          />
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>

  <!-- 列设置弹窗：保留原始样式 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 25%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 数量编辑弹窗：新增用于编辑8个数量字段 -->
  <el-dialog
    title="编辑数量信息"
    v-model="quantityDialogVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form ref="quantityFormRef" :model="currentRow" label-width="120px">
      <el-form-item label="销售数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewSaleQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassSaleQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassSaleQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassSaleQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="配餐数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="quantityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleQuantitySave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件（完全保留原始） -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <ProduceRecordForm ref="formRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElTableV2 } from 'element-plus'
import type { Column } from 'element-plus'
import { ElTag, ElInput, ElButton, ElIcon, ElTooltip, ElCheckboxGroup, ElCheckbox, ElDialog, ElForm, ElFormItem, ElRow, ElCol } from 'element-plus'
import { Search, Refresh, Plus, Setting, Timer } from '@element-plus/icons-vue'

// 保留原始所有业务导入
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'
import { QuarterPlanApi } from '@/api/distm/quarterplan'

/** 基础配置（保留原始） */
defineOptions({ name: 'ScheduleRecord' })
const message = useMessage()
const { t } = useI18n()

// 状态管理：新增数量编辑弹窗相关变量
const loading = ref(true)
const list = ref<ScheduleRecordVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000,
  flightNo: undefined,
  depTime: undefined,
  flightCrew: undefined,
  inboundFlight: undefined,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined,
  recordDate: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 数量编辑弹窗相关
const quantityDialogVisible = ref(false)
const currentRow = ref<Partial<ScheduleRecordVO>>({})
const quantityFormRef = ref()

/** 生产状态（完全保留原始） */
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

/** 工具函数：更新数量列相关判断 */
const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) return '未开始'
  const numStatus = Number(statusValue)
  const matched = pstatusList.find(item => item.value === numStatus)
  return matched ? matched.label : '未开始'
}

const formatTimeArray = (timeArr: any[]) => {
  if (!Array.isArray(timeArr) || timeArr.length !== 2) return ''
  const hour = String(timeArr[0]).padStart(2, '0')
  const minute = String(timeArr[1]).padStart(2, '0')
  return `${hour}:${minute}`
}

const normalizeTimeFormat = (timeValue: any): string => {
  if (!timeValue) return ''
  if (Array.isArray(timeValue) && timeValue.length === 2) return formatTimeArray(timeValue)
  if (typeof timeValue === 'string') {
    if (/^\d{2}:\d{2}$/.test(timeValue)) return timeValue
    if (/^\d{4}$/.test(timeValue)) return `${timeValue.slice(0,2)}:${timeValue.slice(2,4)}`
  }
  return ''
}

const formatTimeString = (timeString: string): string | null => {
  if (timeString.includes(':')) return timeString
  if (!/^\d{4}$/.test(timeString)) return null
  const hours = parseInt(timeString.slice(0,2))
  const minutes = parseInt(timeString.slice(2,4))
  if (hours >=0 && hours <24 && minutes >=0 && minutes <60) {
    return `${String(hours).padStart(2,'0')}:${String(minutes).padStart(2,'0')}`
  }
  return null
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

// 更新数量列判断：包含8个数量字段
const isNumberColumn = (prop: string): boolean => {
  return [
    'crewQty',
    'bussClassQty',
    'premEcoClassQty',
    'ecoClassQty',
    'crewSaleQty',
    'bussClassSaleQty',
    'premEcoClassSaleQty',
    'ecoClassSaleQty'
  ].includes(prop)
}

const getColumnNameByProp = (prop: string): string => {
  const column = tableColumns.find((col) => col.prop === prop)
  return column?.label || prop
}

/** 业务逻辑：更新数量相关处理 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getOthScheduleRecordPage(queryParams)
    list.value = data.list || []
    list.value.forEach((item) => {
      item._original = JSON.parse(JSON.stringify(item))
      // 时间字段格式化
      item.inboundTime = item.inboundTime ? (Array.isArray(item.inboundTime) ? formatTimeArray(item.inboundTime) : normalizeTimeFormat(item.inboundTime)) : ''
      item.preLandingTime = item.preLandingTime ? (Array.isArray(item.preLandingTime) ? formatTimeArray(item.preLandingTime) : normalizeTimeFormat(item.preLandingTime)) : ''
      item.depTime = item.depTime ? (Array.isArray(item.depTime) ? formatTimeArray(item.depTime) : normalizeTimeFormat(item.depTime)) : ''
      // 保存格式化原始值（包含8个数量字段）
      item.formattedOriginal = {
        inboundTime: item.inboundTime || '',
        preLandingTime: item.preLandingTime || '',
        depTime: item.depTime || '',
        machineNo: item.machineNo || '',
        airportStands: item.airportStands || '',
        inboundFlight: item.inboundFlight || '',
        remarks: item.remarks || '',
        // 8个数量字段
        crewQty: item.crewQty || '',
        bussClassQty: item.bussClassQty || '',
        premEcoClassQty: item.premEcoClassQty || '',
        ecoClassQty: item.ecoClassQty || '',
        crewSaleQty: item.crewSaleQty || '',
        bussClassSaleQty: item.bussClassSaleQty || '',
        premEcoClassSaleQty: item.premEcoClassSaleQty || '',
        ecoClassSaleQty: item.ecoClassSaleQty || '',
        specialRemarks: item.specialRemarks || ''
      }
    })
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  if (formRef.value && flightNo) formRef.value.openFlightNo(type, flightNo)
}

const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  if (formAddRef.value && flightNo) formAddRef.value.openAdd('create', flightNo, recordDate)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ScheduleRecordApi.deleteScheduleRecord(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const addToSchedule = async (id: number, flightNo?: string) => {
  try {
    await message.confirm(`确认将航班${flightNo}添加到今日计划中吗？`)
    await ScheduleRecordApi.addToScheduleRecord(id)
    message.success(t('common.success'))
    await getList()
  } catch {}
}

const addAllToSchedule = async () => {
  try {
    await message.confirm(`确认将全部航班添加到今日计划中吗？`)
    await ScheduleRecordApi.addAllToScheduleRecord()
    message.success(t('common.success'))
    await getList()
  } catch {}
}

const importFormRef  = ref(null)
const handleImportLog = () => importFormRef.value?.open()

// 更新字段变更处理：支持8个数量字段
const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }

    const hasChange = Object.keys(row).some((key) => {
      if (key === '_original' || key === 'formattedOriginal') return false
      const original = row.formattedOriginal[key] || ''
      const current = row[key] || ''
      if (isTimeColumn(key)) return original !== current
      if (isNumberColumn(key)) return String(original) !== String(current)
      return original !== current
    })

    if (!hasChange) return

    // 处理8个数量字段的类型转换
    const updateData = {
      ...row,
      crewQty: row.crewQty ? Number(row.crewQty) : undefined,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined,
      crewSaleQty: row.crewSaleQty ? Number(row.crewSaleQty) : undefined,
      bussClassSaleQty: row.bussClassSaleQty ? Number(row.bussClassSaleQty) : undefined,
      premEcoClassSaleQty: row.premEcoClassSaleQty ? Number(row.premEcoClassSaleQty) : undefined,
      ecoClassSaleQty: row.ecoClassSaleQty ? Number(row.ecoClassSaleQty) : undefined
    } as ScheduleRecordVO
    await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(t('common.updateSuccess'))

    row._original = JSON.parse(JSON.stringify(row))
    row.formattedOriginal = {
      inboundTime: row.inboundTime || '',
      preLandingTime: row.preLandingTime || '',
      depTime: row.depTime || '',
      machineNo: row.machineNo || '',
      airportStands: row.airportStands || '',
      inboundFlight: row.inboundFlight || '',
      remarks: row.remarks || '',
      // 8个数量字段
      crewQty: row.crewQty || '',
      bussClassQty: row.bussClassQty || '',
      premEcoClassQty: row.premEcoClassQty || '',
      ecoClassQty: row.ecoClassQty || '',
      crewSaleQty: row.crewSaleQty || '',
      bussClassSaleQty: row.bussClassSaleQty || '',
      premEcoClassSaleQty: row.premEcoClassSaleQty || '',
      ecoClassSaleQty: row.ecoClassSaleQty || '',
      specialRemarks: row.specialRemarks || ''
    }
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('更新失败:', err)
    await getList()
  }
}

/** 输入框事件：支持8个数量字段处理 */
const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleColumnTimeBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && /^\d{2}:\d{2}$/.test(current)) {
    await handleFieldChange(row)
    return
  }

  if (current && (current.length !== 4 || !/^\d{4}$/.test(current))) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`)
    row[prop] = original
    return
  }

  if (current) {
    const formatted = formatTimeString(current)
    if (formatted) {
      if (formatted === original) {
        row[prop] = formatted
        return
      }
      row[prop] = formatted
      await handleFieldChange(row)
    } else {
      message.error('请输入有效的时间格式(HHmm)')
      row[prop] = original
    }
  } else {
    if (original !== '') await handleFieldChange(row)
  }
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleNumberBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) < 0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return
  await handleFieldChange(row)
}

/** 搜索表单时间处理（保留原始） */
const handleTimeInput = (field: string, value: string) => {
  queryParams[field] = value.replace(/[^0-9]/g, '')
}

const handleTimeBlur = (field: string) => {
  const value = queryParams[field]
  if (!value) return
  if (/^\d{2}:\d{2}$/.test(value)) return
  if (value.length !== 4 || !/^\d{4}$/.test(value)) {
    message.error('请输入4位数字的时间格式(HHmm)')
    queryParams[field] = ''
    return
  }
  const formatted = formatTimeString(value)
  queryParams[field] = formatted || ''
  if (!formatted) message.error('请输入有效的时间格式(HHmm)')
}

/** 数量编辑弹窗处理函数 */
const openQuantityEdit = (row: ScheduleRecordVO) => {
  currentRow.value = JSON.parse(JSON.stringify(row))
  quantityDialogVisible.value = true
}

const handleQuantitySave = async () => {
  try {
    if (!currentRow.value.id) {
      message.error('数据无效')
      return
    }
    const tempRow = JSON.parse(JSON.stringify(currentRow.value)) as ScheduleRecordVO
    await handleFieldChange(tempRow)
    quantityDialogVisible.value = false
    await getList()
  } catch (err) {
    console.error('数量更新失败:', err)
    message.error(t('common.updateFail'))
  }
}

/** 列设置：更新表格列定义（将3个数量列改为1个复合列） */
const tableColumns = [
  { prop: 'carInfo', label: '车辆信息', width: 150, editable: true, editWidth: 120, type: '文本' },
  { prop: 'flightCrew', label: '航机员', width: 150, editable: true, editWidth: 120, type: '文本' },
  { prop: 'inboundFlight', label: '进港航班', width: 150, editable: true, editWidth: 120, type: '文本' },
  { prop: 'flightNo', label: '航班号', width: 120, type: '文本' },
  { prop: 'machineNo', label: '机号', width: 140, editable: true, editWidth: 110, type: '文本' },
  { prop: 'inboundTime', label: '进港时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'preLandingTime', label: '预落时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'airportStands', label: '机位', width: 130, editable: true, editWidth: 100, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'remarks', label: '备注', width: 200, editable: true, editWidth: 200, type: '文本' },
  // 替换原3个数量列为1个复合列（包含8个数量字段）
  {
    prop: 'quantity',
    label: '数量',
    width: 300,
    type: '复合'
  },
  { prop: 'specialRemarks', label: '特殊说明', width: 200, editable: true, editWidth: 200, type: '文本' },
  { prop: 'aircraftType', label: '机型', width: 120, type: '文本' },
  { prop: 'airlineComp', label: '所属公司', width: 120, type: '文本' },
  { prop: 'company', label: '所属公司', width: 120, type: '文本' },
  { prop: 'recordDate', label: '日期', width: 120, type: '日期' },
  { prop: 'createTime', label: '创建时间', width: 180, type: '时间' },
  { prop: 'pstatus', label: '生产状态', width: 120, type: '状态' }
]

// 列显示控制（保留原始逻辑）
const columnVisibility = ref<Record<string, boolean>>({})
const selectedColumns = ref<string[]>([])
const columnSettingVisible = ref(false)

const initColumnVisibility = () => {
  const visibility: Record<string, boolean> = {}
  const selected: string[] = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

const openColumnSetting = () => {
  columnSettingVisible.value = true
}

const saveColumnSettings = () => {
  const newVisibility: Record<string, boolean> = {}
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })
  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

/** 虚拟化表格列配置：渲染复合数量列（包含8个字段） */
const tableV2Columns = computed<Column<ScheduleRecordVO>[]>(() => {
  const visibleColumns = tableColumns.filter(column => columnVisibility.value[column.prop])

  const baseColumns = visibleColumns.map(column => ({
    key: column.prop,
    title: column.label,
    dataKey: column.prop,
    width: column.width || 120,
    cellRenderer: ({ cellData, rowData }) => {
      const row = rowData as ScheduleRecordVO
      const cellValue = cellData?.toString() || ''

      // 渲染复合数量列（包含8个数量字段）
      if (column.prop === 'quantity') {
        return (
          <div 
            style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
            onClick={() => openQuantityEdit(row)}
          >
            {/* 标题行 */}
            <div style="display: flex; font-weight: 500; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">J</div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">S</div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">G</div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">Y</div>
            </div>
            
       
            
           
                 {/* 销售数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.crewSaleQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.bussClassSaleQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.premEcoClassSaleQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.ecoClassSaleQty || '-'}
              </div>
            </div>
             {/* 数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.crewQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.bussClassQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.premEcoClassQty || '-'}
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {row.ecoClassQty || '-'}
              </div>
            </div>
          </div>
        )
      }

      // 可编辑列渲染（保留原始逻辑）
      if (column.editable) {
        if (isTimeColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => { row[column.prop] = val }}
              placeholder={`请输入${column.label}(HHmm)`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
              onBlur={() => handleColumnTimeBlur(row, column.prop)}
              showWordLimit
            />
          )
        }

        if (isNumberColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => { row[column.prop] = val }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onInput={(e) => handleNumberInput(row, column.prop, e.target.value)}
              onBlur={() => handleNumberBlur(row, column.prop)}
              showWordLimit
            />
          )
        }

        return (
          <ElInput
            modelValue={cellValue}
            onUpdate:modelValue={(val) => { row[column.prop] = val }}
            placeholder={`请输入${column.label}`}
            clearable
            class={`!w-${column.editWidth || 100}px`}
            onBlur={() => handleTextBlur(row, column.prop)}
            showWordLimit
          />
        )
      }

      // 特殊列渲染（保留原始）
      if (column.prop === 'pstatus') {
        return <ElTag type="primary">{getStatusLabel(cellData)}</ElTag>
      }

      if (column.prop === 'createTime') {
        return <ElTooltip content={formatDate(cellData) || '-'}>
          <span class="flex items-center">
            <ElIcon class="mr-2"><Timer /></ElIcon>
            {formatDate(cellData) || '-'}
          </span>
        </ElTooltip>
      }

      if (isTimeColumn(column.prop)) {
        return <ElTooltip content={formatTimeString(cellValue) || '-'}>
          <span>{formatTimeString(cellValue) || '-'}</span>
        </ElTooltip>
      }

      return <span>{cellValue || '-'}</span>
    }
  }))

  // 操作列（保留原始）
  const actionColumn: Column<ScheduleRecordVO> = {
    key: 'operations',
    title: '操作',
    width: 180,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as ScheduleRecordVO
      return (
        <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => addToSchedule(row.id, row.flightNo)}
          >
            添加到今日计划
          </ElButton>
          <ElButton
            type="danger"
            link
            size="small"
            onClick={() => handleDelete(row.id)}
          >
            删除
          </ElButton>
        </div>
      )
    }
  }

  return [...baseColumns, actionColumn]
})

/** 辅助配置（保留原始） */
const tableRowClassName = ({ rowData }: { rowData: any }) => {
  return rowData?.markStatus === 1 ? 'row-first' : ''
}

/** 自动刷新（保留原始） */
const refreshInterval = ref(120000)
const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)
const autoRefreshEnabled = ref(true)

const startAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
  autoRefreshTimer.value = setInterval(() => getList(), refreshInterval.value)
}

const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
}

/** 初始化（保留原始） */
onMounted(async () => {
  initColumnVisibility()
  try {
    await getList()
    if (autoRefreshEnabled.value) startAutoRefresh()
  } catch (err) {
    message.error('页面初始化失败')
  }
})

onUnmounted(() => stopAutoRefresh())
</script>

<style scoped>
/* 保留原始所有样式 */
:deep(.el-table__row.row-first),
:deep(.el-table-v2__row.row-first) {
  background-color: #f26a6e !important;
}

:deep(.el-input__inner) {
  width: 100% !important;
  min-height: 28px !important;
}
:deep(.el-table-v2__cell) {
  padding: 4px 8px !important;
}
:deep(.el-table td),
:deep(.el-table th) {
  padding: 8px 0 !important;
}

.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}
:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

:deep(.el-table th),
:deep(.el-table-v2__header) {
  background-color: #f8fafc !important;
}
:deep(.el-input) {
  margin: 0 !important;
}
</style>
